﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using Newtonsoft.Json;

namespace working
{
    public partial class BackupForm : Form
    {
        private BackupInfo info;
        private string id;
        private bool changed;
        public Action onChange { get; set; }
        private OpenFileDialog ofd;
        private SaveFileDialog sfd;

        public BackupForm()
        {
            InitializeComponent();
            info = new BackupInfo();
            ofd = new OpenFileDialog();
            sfd = new SaveFileDialog();
            listView_paths.Items.Clear();
            listView_names.Items.Clear();
            rootPath_textBox.TextChanged += OnRootPathChanged;

            listView_paths.MouseClick += OnClickPathItem;
            listView_names.MouseClick += OnClickNameItem;
        }
        #region events

        private void OnRootPathChanged(object sender, EventArgs e)
        {
            info.rootPath = rootPath_textBox.Text;
        }
        private void export_Click(object sender, EventArgs e)
        {
            var folder = info.rootPath;
            ExportToFolder(folder);
        }
        private void export2_Click(object sender, EventArgs e)
        {
            var result = Util.OpenFolderDialog("选择导出目录", info.rootPath);
            if (!string.IsNullOrEmpty(result))
            {
                ExportToFolder(result);
            }
        }

        private void ExportToFolder(string folder)
        {
            var selectedName = GetSelectedNameItem();
            if (!string.IsNullOrEmpty(selectedName))
            {
                var backup =System.IO.Path.Combine(Util.GetBackupFolder(id), selectedName);
                if(System.IO.Directory.Exists(backup))
                {
                    Util.CopyFilesTo(backup, folder);
                    Util.OpenSelectFolder(folder);
                }
                else if (System.IO.File.Exists(backup + ".zip"))
                {
                    CompressUtil.UnCompress(backup + ".zip", folder);
                    Util.OpenSelectFolder(folder);
                }
                else
                {
                    MessageBox.Show("备份丢失：" + backup);
                }
            }
            else
            {
                MessageBox.Show("未选择需要导出的备份！");
            }
        }

        private string GetSelectedNameItem()
        {
            if (listView_names.SelectedItems.Count > 0)
            {
                var item0 = listView_names.SelectedItems[0];
                return item0.Text;
            }
            else
            {
                return null;
            }

        }

        private void add_folder_Click(object sender, EventArgs e)
        {
            var result = Util.OpenFolderDialog("添加关联文件夹", info.rootPath);
            if (!string.IsNullOrEmpty(result))
            {
                string file = result;
                if (TryClip(ref file))
                {
                    info.paths.Add(file);
                    changed = true;
                    ShowBackInfoList();
                }
            }
        }

        private void add_file_Click(object sender, EventArgs e)
        {
            if (!string.IsNullOrEmpty(info.rootPath))
            {
                ofd.InitialDirectory = info.rootPath;
            }
            ofd.Multiselect = true;
            ofd.ShowHelp = true;
            ofd.Title = "添加关联文件";
            ofd.Filter = "All Files (*.*)|*.*";
            var result = ofd.ShowDialog();
            if (result == DialogResult.OK)
            {
                for (int i = 0; i < ofd.FileNames.Length; i++)
                {
                    var file = ofd.FileNames[i];
                    if(TryClip(ref file)){
                        info.paths.Add(file);
                        changed = true;
                    }
                }
                if (changed)
                {
                    ShowBackInfoList();
                }
            }
        }

        private void createCopy_Click(object sender, EventArgs e)
        {
            if (string.IsNullOrEmpty(id))
                id = System.Guid.NewGuid().ToString();

            if (!CheckFileCliped())
            {
                MessageBox.Show("存在绝对路径，请先裁切后创建拷贝");
                return;
            }

            if (string.IsNullOrEmpty(copyName_textBox.Text))
                return;

            if (info.paths.Count == 0)
                return;

            //var targetFolder = System.IO.Path.Combine(Util.GetBackupFolder(id), copyName_textBox.Text);

            //foreach (var path in info.paths)
            //{
            //    var currentPath = path;
            //    var rePath = "";
            //    var targetPath = targetFolder;
            //    if (!string.IsNullOrEmpty(info.rootPath) && path.Contains(info.rootPath))
            //    {
            //        rePath = path.Replace(info.rootPath, "");
            //        targetPath = System.IO.Path.Combine(targetPath, rePath);
            //    }
            //    else
            //    {
            //        currentPath = System.IO.Path.Combine(info.rootPath, path);
            //        targetPath = System.IO.Path.Combine(targetPath, path);
            //    }
            //    Util.Copy(currentPath, targetPath);
            //}

            var targetZip = System.IO.Path.Combine(Util.GetBackupFolder(id), copyName_textBox.Text) + ".zip";
            CompressUtil.Compress(targetZip, info.rootPath, info.paths);
            UpdateBackDatas();
        }
        private void clear_Click(object sender, EventArgs e)
        {
            info.paths.Clear();
            ShowBackInfoList();
        }
        protected override void OnClosing(CancelEventArgs e)
        {
            e.Cancel = true;
            base.OnClosing(e);
            Hide();

            if (changed && onChange != null)
            {
                onChange.Invoke();
            }
        }
        #endregion
        public void ShowBackUp(string id, BackupInfo backInfo)
        {
            this.id = id;
            this.info = backInfo;
            if (info != null)
            {
                Show();
                ShowBackInfoList();
                UpdateBackDatas();
            }
        }

        private bool CheckFileCliped()
        {
            foreach (var path in info.paths)
            {
                var root = System.IO.Path.GetPathRoot(path);
                if (!string.IsNullOrEmpty(root))
                {
                    return false;
                }
            }
            return true;
        }
        private void ShowBackInfoList()
        {
            if (info != null)
            {
                listView_paths.Items.Clear();

                rootPath_textBox.Text = info.rootPath;
                foreach (var path in info.paths)
                {
                    ListViewItem li_item = new ListViewItem();
                    li_item.ToolTipText = li_item.Text = path;
                    listView_paths.Items.Add(li_item);
                }

                listView_paths.Update();
            }
        }

        private void UpdateBackDatas()
        {
            if (info != null)
            {
                var folder = Util.GetBackupFolder(id);
                var childFolders = System.IO.Directory.GetDirectories(folder);
                listView_names.Items.Clear();

                foreach (var path in childFolders)
                {
                    ListViewItem li_item = new ListViewItem();
                    li_item.ToolTipText = li_item.Text = System.IO.Path.GetFileName(path);
                    listView_names.Items.Add(li_item);
                }

                var childZips = System.IO.Directory.GetFiles(folder,"*.zip");
                foreach (var path in childZips)
                {
                    ListViewItem li_item = new ListViewItem();
                    li_item.ToolTipText = li_item.Text = System.IO.Path.GetFileNameWithoutExtension(path);
                    listView_names.Items.Add(li_item);
                }

                listView_names.Update();
            }
        }

        private bool TryClip(ref string path)
        {
            if (string.IsNullOrEmpty(info.rootPath))
                return false;
            if (string.IsNullOrEmpty(System.IO.Path.GetPathRoot(info.rootPath)))
                return false;

            if (path.Contains(info.rootPath)){
                path = path.Replace(info.rootPath, "");
                if(path.StartsWith("\\")){
                    path = path.Substring(1);
                }
                return true;
            }
            return false;
        }

        private void 删除ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            var item0 = listView_paths.SelectedItems[0];
            if (!string.IsNullOrEmpty(item0.Text))
            {
                info.paths.Remove(item0.Text);
                changed = true;
                ShowBackInfoList();
            }
        }

        private void toolStripMenuItem1_Click(object sender, EventArgs e)
        {
            var selectedName = GetSelectedNameItem();
            if (!string.IsNullOrEmpty(selectedName))
            {
                MessageBoxButtons messButton = MessageBoxButtons.OKCancel;
                DialogResult rt = MessageBox.Show("此操作会删除相关的存档，继续？", "删除确认", messButton);
                if (rt == DialogResult.Cancel){
                    return;
                }
                var path = System.IO.Path.Combine(Util.GetBackupFolder(id), selectedName);
                if (System.IO.Directory.Exists(path))
                {
                    FileEx.SendToRecyclyBin(path + "\0\0", true);
                    changed = true;
                    UpdateBackDatas();
                }
                else if(System.IO.File.Exists(path + ".zip"))
                {
                    FileEx.SendToRecyclyBin(path + ".zip", true);
                    changed = true;
                    UpdateBackDatas();
                }
            }
        }


        private void OnClickNameItem(object sender, MouseEventArgs e)
        {
            copyName_textBox.Text = GetSelectedNameItem();
            if (e.Button == MouseButtons.Right)
            {
                contextMenuStrip2.Show(MousePosition);
            }
        }

        private void OnClickPathItem(object sender, MouseEventArgs e)
        {
            if (e.Button == MouseButtons.Right)
            {
                contextMenuStrip1.Show(MousePosition);
            }
        }

        private void OnWorkDir_Click(object sender, EventArgs e)
        {
            var result = Util.OpenFolderDialog("选择工作目录", info.rootPath);
            if (!string.IsNullOrEmpty(result))
            {
                info.rootPath = rootPath_textBox.Text = result;
                //changed = true;
            }
        }

        private void 打开文件位置ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            var selectedName = GetSelectedNameItem();
            if (!string.IsNullOrEmpty(selectedName))
            {
                var path = System.IO.Path.Combine(Util.GetBackupFolder(id), selectedName);
                if (System.IO.Directory.Exists(path))
                {
                    Util.OpenSelectFolder(path);
                }
                else if(System.IO.File.Exists(path + ".zip"))
                {
                    Util.OpenFolderAndSelectFile(path + ".zip");
                }
            }
        }

        private void importJson_Click(object sender, EventArgs e)
        {
            if (!string.IsNullOrEmpty(info.rootPath)){
                ofd.InitialDirectory = info.rootPath;
            }
            ofd.Multiselect = false;
            ofd.ShowHelp = false;
            ofd.Title = "选择列表文件";
            ofd.Filter = "列表配制 (*.json)|*.json";
            var result = ofd.ShowDialog();
            if (result == DialogResult.OK)
            {
                var text = System.IO.File.ReadAllText(ofd.FileName);
                if(!string.IsNullOrEmpty(text))
                {
                    var list = JsonConvert.DeserializeObject<List<string>>(text);
                    if (list != null)
                    {
                        info.paths.Clear();
                        info.paths.AddRange(list);
                        changed = true;
                        ShowBackInfoList();
                    }
                }
            }
        }
        private void exportJson_Click(object sender, EventArgs e)
        {
            if (!string.IsNullOrEmpty(info.rootPath))
            {
                sfd.InitialDirectory = info.rootPath;
            }
            sfd.ShowHelp = false;
            sfd.Title = "保存列表文件";
            sfd.Filter = "列表配制 (*.json)|*.json";
            var result = sfd.ShowDialog();
            if (result == DialogResult.OK)
            {
                var jsonText = JsonConvert.SerializeObject(info.paths);
                System.IO.File.WriteAllText(sfd.FileName, jsonText);
                Util.OpenFolderAndSelectFile(sfd.FileName);
            }
            
        }
    }
}
